package com.varian.rabbit.interceptor;

import cn.hutool.core.convert.Convert;
import com.varian.tool.Func;
import com.varian.tool.log.TraceIdContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.amqp.core.Message;

/**
 * @author ben
 * @since 2024/9/18
 */
@Slf4j
public class RabbitListenerInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        try {
            for (Object object : invocation.getArguments()) {
                if (object instanceof Message message) {
                    TraceIdContextHolder.set(Convert.toStr(message.getMessageProperties().getHeader(Func.TRACE_ID)));
                    log.info("RabbitListenerInterceptor: {}", message);
                }
            }
            return invocation.proceed();
        } finally {
            TraceIdContextHolder.remove();
        }
    }
}
